#!/bin/bash

usage() {
cat << EOF
usage: $0 options

Show the validity of certificates in the current directory.

OPTIONS:
   -h  Show this message
   -o  Show 'OK' certificates
   -e  Show 'EXPIRING' certificates
   -p  Show 'EXPIRED' certificates

By default, all types will be shown
EOF
}

CERTS_OK=
CERTS_EXPIRED=
CERTS_EXPIRING=
while getopts "hoep" OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         o)
             CERTS_OK=1
             ;;
         e)
             CERTS_EXPIRING=1
             ;;
         p)
             CERTS_EXPIRED=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $CERTS_OK ]] &&  [[ -z $CERTS_EXPIRED ]] && [[ -z $CERTS_EXPIRING ]]; then
	CERTS_OK=1
	CERTS_EXPIRED=1
	CERTS_EXPIRING=1
fi

OK="\e[1;32mOK\e[0m"
EXPIRING="\e[1;33mEXPIRING\e[0m"
EXPIRED="\e[1;31mEXPIRED\e[0m"

TODAY=$(date '+%s')

for CERT in `ls *.crt`; do 
	ENDDATE=$(openssl x509 -in $CERT -noout -enddate 2>/dev/null)
	
	if grep -q "notAfter" <<< "$ENDDATE" ; then
		# Convert = to space and read variables
		read notAfter M D hms Y GMT <<< ${ENDDATE//[=]/ }

		DATE=$(date -d "$D $M $Y $hms" '+%s')
		# 60 days in seconds
		EXP_DATE_DELTA=5184000

		if [[ $TODAY -gt $DATE ]]; then
			[[ $CERTS_EXPIRED ]] && echo -e "$CERT has $EXPIRED (${ENDDATE//notAfter=/})"
		elif [[ $TODAY -gt $((DATE-EXP_DATE_DELTA)) ]]; then
			[[ $CERTS_EXPIRING ]] && echo -e "$CERT is $EXPIRING soon (${ENDDATE//notAfter=/})"
		else
			[[ $CERTS_OK ]] && echo -e "$CERT is $OK (${ENDDATE//notAfter=/})"
		fi
	fi
done

